<template>
	<div class="address-list">
		<van-address-list v-model="chosenAddressId" :list="addressList" default-tag-text="默认" add-button-text="+添加地址"
			@select="onSelect" @add="onAdd" @edit="onEdit" />
	</div>
</template>

<script>
	import {
		showToast
	} from 'vant';
	import {
		getAddressListAPI
	} from "@/api/address.js";

	export default {
		data() {
			return {
				chosenAddressId: "",
				addressList: []
			};
		},
		created() {
			const addressId = this.$route.params.addressId;
			if (addressId && typeof addressId !== 'string') {
				console.error('地址ID参数格式不正确');
				return;
			}
			this.chosenAddressId = addressId || "";
			this.getAddressList();
		},
		methods: {
			navigateToAddressEdit(id) {
				this.$router.push({
					name: "addressEdit",
					params: {
						id
					}
				});
			},
			onAdd() {
				this.navigateToAddressEdit();
			},
			onEdit(item) {
				this.navigateToAddressEdit(item.id);
			},
			getAddressList() {
				getAddressListAPI().then(result => {
					this.addressList = result.data.map(item => {
						const {
							id,
							name,
							tel
						} = item;
						const address = item.city + item.county + item.address_detail;
						const isDefault = item.is_default === 1;
						return {
							id,
							name,
							tel,
							address,
							isDefault
						};
					});
					const defaultAddress = this.addressList.find(item => item.isDefault);
					if (defaultAddress) {
						this.chosenAddressId = defaultAddress.id;
					}
				}).catch(error => {
					console.error('获取地址列表失败:', error);
					showToast('获取地址列表失败，请稍后重试');
				});
			},
			onSelect(item) {
				const addressId = item.id;
				if (this.$route.params.addressId) {
					this.$router.replace({
						name: "orderCreate",
						params: {
							addressId
						}
					});
				}
			}
		}
	};
</script>

<style scoped lang="less">
	@bgColor: #f4f4f4;
	@mainColor: #e74c3c;
	@textColor: #333;
	@secondaryColor: #777;

	.address-list {
		min-height: 100vh;
		background: @bgColor;
		padding: 15px;

		::deep.van-address-list {
			border-radius: 10px;
			box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1);
			background-color: #fff;

			margin-top: 0;
			padding: 15px;

			.van-address-item {
				border-radius: 8px;
				margin-bottom: 10px;
				padding: 15px;
				border: 1px solid #e0e0e0;
				transition: all 0.3s ease;

				&:hover {
					box-shadow: 0 0.1rem 0.3rem rgba(0, 0, 0, 0.08);
				}

				.van-address-item__content {
					color: @textColor;
					font-size: 14px;
				}

				.van-address-item__meta {
					color: @secondaryColor;
					font-size: 12px;
					margin-top: 5px;
				}
			}

			.van-radio__icon--checked.van-icon {
				background: @mainColor;
				border-color: @mainColor;
			}

			.van-button--danger {
				background: @mainColor;
				border-radius: 5px;
				padding: 8px 16px;
				font-size: 14px;
				transition: background 0.3s ease;

				&:hover {
					background: #c0392b;
				}
			}
		}
	}
</style>